package com.huahan.auth.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.huahan.auth.Utils.RandomValidateCodeUtil;
import com.huahan.auth.domain.UserInfo;
import com.huahan.auth.exception.BusinessException;
import com.huahan.auth.service.UserInfoService;
import com.mall.common.constant.LoginInfoParam;
import com.mall.common.constant.ResultCode;
import com.mall.common.utils.R;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/pc/login")
public class PcLoginController {
    public static Logger logger = LoggerFactory.getLogger(PcLoginController.class);
    @Autowired
    private UserInfoService userInfoService;
    @Lazy
    @Resource
    private PasswordEncoder passwordEncoder;


    /**
     * 账号密码登录
     *
     * @param loginInfoParam
     * @return
     */
    @PostMapping("/loginByPwd")
    public R loginByPwd(LoginInfoParam loginInfoParam) {
        String phone = loginInfoParam.getPhone();
        if (StringUtils.isEmpty(phone)) {
            throw new BusinessException(ResultCode.ACCOUNT_IS_EMPTY);
        }
        String password = loginInfoParam.getPassword();
        if (StringUtils.isEmpty(password)) {
            throw new BusinessException(ResultCode.PASSWORD_IS_EMPTY);
        }
        String verifyCode = loginInfoParam.getVerifyCode();
        if (StringUtils.isEmpty(verifyCode)) {
            throw new BusinessException(ResultCode.SMS_CODE_IS_EMPTY);
        }
//        if(!redisTemplate.hasKey(RandomValidateCodeUtil.RANDOMCODEKEY+"PC"+verifyCode)){
//            throw new BusinessException(ResultCode.SMS_CODE_ERROR);
//        }else{
//            // 删除验证码
//            redisTemplate.delete(RandomValidateCodeUtil.RANDOMCODEKEY+"PC"+loginInfoParam.getVerifyCode());
//        }
        Map<String, Object> map = new HashMap<>();
        map.put("phone_number", phone);
        map.put("is_pc", "1");
        List<UserInfo> list = userInfoService.listByMap(map);
        if (list.size()<1 ) {
            //用户信息不存在
            return R.error(ResultCode.USER_INFO_NOT_EXIST.getMessage());
        }
        UserInfo userInfoDO = list.get(0);
        List<UserInfo> checkStstus = list.stream()
                .filter(userInfo -> "1".equals(userInfo.getStatus()))
                .collect(Collectors.toList());
        if(CollectionUtil.isNotEmpty(checkStstus)){
            return R.error("用户已禁用");
        }
        if (!passwordEncoder.matches(password, userInfoDO.getPassword())) {
            //密码错误
            return R.error(ResultCode.ACCOUNT_OR_PASSWORD_ERROR.getMessage());
        }
        loginInfoParam.setFlag("1");
        loginInfoParam.setType(userInfoDO.getEmpType().toString());
        return userInfoService.pwdLogin(loginInfoParam);
    }

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 生成验证码
     */
    @GetMapping(value = "/getVerify")
    public void getVerify(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片
            response.setHeader("Pragma", "No-cache");//设置响应头信息，告诉浏览器不要缓存此内容
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);
            RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();
            randomValidateCode.getRandcodePC(request, response, redisTemplate);//输出验证码图片方法
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取验证码失败>>>> ", e);
        }
    }


}
